package com.netmi.myjectpack.paging

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.paging.LoadState
import androidx.recyclerview.widget.LinearLayoutManager
import com.netmi.myjectpack.R
import com.netmi.myjectpack.databinding.ActivityMainBinding
import com.netmi.myjectpack.databinding.Paging3ActivityMainBinding
import com.netmi.myjectpack.paging.adapter.RepoAdapter
import com.netmi.myjectpack.paging.bean.Page3ViewModel
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch


/**
 *
 * 参考：
 * https://guolin.blog.csdn.net/article/details/114707250?spm=1001.2014.3001.5502
 * https://developer.android.com/codelabs/android-paging#12
 */
class Paging3MainActivity : AppCompatActivity() {
    private lateinit var binding: Paging3ActivityMainBinding
    private val viewModel by lazy { ViewModelProvider(this).get(Page3ViewModel::class.java) }

    private val repoAdapter = RepoAdapter()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.paging3_activity_main)

        binding.recyclerView.layoutManager = LinearLayoutManager(this)
        binding.recyclerView.adapter = repoAdapter
        lifecycleScope.launch {
            viewModel.getPagingData().collect { pagingData ->
                repoAdapter.submitData(pagingData)
            }
        }
        repoAdapter.addLoadStateListener {
            when (it.refresh) {
                is LoadState.NotLoading -> {
                    binding.progressBar.visibility = View.INVISIBLE
                    binding.recyclerView.visibility = View.VISIBLE
                }
                is LoadState.Loading -> {
                    binding.progressBar.visibility = View.VISIBLE
                    binding.recyclerView.visibility = View.INVISIBLE
                }
                is LoadState.Error -> {
                    val state = it.refresh as LoadState.Error
                    binding.progressBar.visibility = View.INVISIBLE
                    Toast.makeText(
                        this,
                        "Load Error: ${state.error.message}",
                        Toast.LENGTH_SHORT
                    ).show()
                }
            }
        }

    }


}